#include "InvoiceStatistics.h"
#include <QSqlRecord>
#include <QDate>
#include <QHeaderView>

InvoiceStatistics::InvoiceStatistics(QWidget *parent)
    : QWidget(parent)
{
    //setWindowTitle("发票统计系统");
    //resize(800, 600);

    // 初始化UI元素
    //QWidget *centralWidget = new QWidget(this);
    //setCentralWidget(centralWidget);

    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    // 日期范围选择区域
    QGroupBox *searchGroupBox = new QGroupBox("日期范围选择");
    QHBoxLayout *searchLayout = new QHBoxLayout(searchGroupBox);

    QLabel *startDateLabel = new QLabel("开始日期:");
    startDateEdit = new QDateEdit(QDate::currentDate().addMonths(-1));
    startDateEdit->setCalendarPopup(true);

    QLabel *endDateLabel = new QLabel("结束日期:");
    endDateEdit = new QDateEdit(QDate::currentDate());
    endDateEdit->setCalendarPopup(true);

    searchButton = new QPushButton("查询");

    searchLayout->addWidget(startDateLabel);
    searchLayout->addWidget(startDateEdit);
    searchLayout->addWidget(endDateLabel);
    searchLayout->addWidget(endDateEdit);
    searchLayout->addWidget(searchButton);
    searchLayout->addStretch();

    // 统计结果区域
    QGroupBox *statsGroupBox = new QGroupBox("统计结果");
    QHBoxLayout *statsLayout = new QHBoxLayout(statsGroupBox);

    totalInvoicesLabel = new QLabel("发票总数: 0");
    totalAmountLabel = new QLabel("金额总数: 0.00");

    statsLayout->addWidget(totalInvoicesLabel);
    statsLayout->addWidget(totalAmountLabel);
    statsLayout->addStretch();

    // 表格视图
    invoiceTableView = new QTableView();
    invoiceTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    invoiceTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    invoiceTableView->setAlternatingRowColors(true);

    mainLayout->addWidget(searchGroupBox);
    mainLayout->addWidget(statsGroupBox);
    mainLayout->addWidget(invoiceTableView);

    // 设置数据库连接
    if (!setupDatabase()) {
        QMessageBox::critical(this, "错误", "数据库连接失败: " + db.lastError().text());
    }

    // 创建表格数据模型
    model = new QSqlTableModel(this, db);
    model->setTable("invoices");
    model->setHeaderData(0, Qt::Horizontal, "发票ID");
    model->setHeaderData(1, Qt::Horizontal, "发票编号");
    model->setHeaderData(2, Qt::Horizontal, "开票日期");
    model->setHeaderData(3, Qt::Horizontal, "总金额");
    model->setHeaderData(4, Qt::Horizontal, "税额");
    model->setHeaderData(5, Qt::Horizontal, "销售方");
    model->setHeaderData(6, Qt::Horizontal, "购买方");

    invoiceTableView->setModel(model);

    // 连接信号和槽
    connect(searchButton, &QPushButton::clicked, this, &InvoiceStatistics::searchInvoices);

    // 初始加载数据
    searchInvoices();
}

InvoiceStatistics::~InvoiceStatistics()
{
    if (db.isOpen()) {
        db.close();
    }
}

bool InvoiceStatistics::setupDatabase()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    // 设置数据库连接参数
    db.setHostName("8.148.65.226");     // 数据库服务器地址8.148.65.226
    db.setPort(3306);                // 端口号
    db.setDatabaseName("malloy"); // 数据库名
    db.setUserName("malloy");          // 用户名
    db.setPassword("Z54EJHWnY3K6xBsN");      // 密码

    // 如果是其他数据库类型，请相应修改连接参数
    // 例如 MySQL:
    // db = QSqlDatabase::addDatabase("QMYSQL");
    // db.setHostName("localhost");
    // db.setDatabaseName("invoices_db");
    // db.setUserName("username");
    // db.setPassword("password");

    return db.open();
}

void InvoiceStatistics::searchInvoices()
{
    QDate startDate = startDateEdit->date();
    QDate endDate = endDateEdit->date();

    // 设置筛选条件
    QString filter = QString("invoice_date >= '%1' AND invoice_date <= '%2'")
                     .arg(startDate.toString("yyyy-MM-dd"))
                     .arg(endDate.toString("yyyy-MM-dd"));

    model->setFilter(filter);
    model->select();

    // 自动调整列宽以适应内容
    invoiceTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    // 计算统计数据
    int invoiceCount = model->rowCount();
    double totalAmount = 0.0;

    for (int i = 0; i < invoiceCount; ++i) {
        QSqlRecord record = model->record(i);
        totalAmount += record.value("total_amount").toDouble();
    }

    // 更新统计标签
    totalInvoicesLabel->setText(QString("发票总数: %1").arg(invoiceCount));
    totalAmountLabel->setText(QString("金额总数: %1").arg(totalAmount, 0, 'f', 2));
}
